package com.duoec.magichour.core.web.freemarker.portlet.common;

import com.duoec.magichour.core.CommonConst;
import com.duoec.magichour.core.utils.MD5Utils;
import com.duoec.magichour.core.web.freemarker.FreemarkerResourceVars;
import com.duoec.magichour.core.web.freemarker.PortletException;
import com.duoec.magichour.core.web.freemarker.portlet.BaseFuturePortlet;
import com.duoec.magichour.core.web.freemarker.portlet.PortletParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.File;

/**
 * Created by ycoe on 16/5/20.
 */
public abstract class ResourcePortlet extends BaseFuturePortlet {
    private static final Logger LOGGER = LoggerFactory.getLogger(ResourcePortlet.class);

    @PortletParam
    protected String src; //引入的js脚本

    protected File getSourceFile() throws PortletException {
        if (StringUtils.isEmpty(src)) {
            return null;
        }
        String srcPath = src;
        if (src.startsWith("http://") || src.startsWith("https://")) {
            //网络资源
            throw new PortletException(env, "暂时不支持网络脚本!");
        }
        if (srcPath.startsWith("/")) {
            srcPath = srcPath.substring(1);
        }
        srcPath = CommonConst.STATIC_PATH + srcPath;
        File resourceFile = new File(srcPath);
        if (!resourceFile.exists()) {
            LOGGER.error("文件不存在:{}", srcPath);
            return null;
        }
        return resourceFile;
    }

    protected String getResourceName(long lastModifyTime) {
        return MD5Utils.md5(resourceVars.getTemplateName() + lastModifyTime);
    }

    protected long getTemplateLastModify() {
        String templateName = this.env.getCurrentTemplate().getSourceName();
        long lastModify = 0L;
        File templateFile = new File(FreemarkerResourceVars.VIEW_DIR + "/" + templateName);
        if (templateFile.exists()) {
            lastModify = templateFile.lastModified();
        }
        return lastModify;
    }
}
